package com.bulletelc.apollopre.manager;

import android.app.Application;

import com.bulletelc.apollopre.constants.GlobalConfig;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.cookie.CookieJarImpl;
import com.lzy.okgo.cookie.store.DBCookieStore;
import com.lzy.okgo.interceptor.HttpLoggingInterceptor;

import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

import okhttp3.OkHttpClient;

/**
 * author: lhl
 * date  : 2017/12/25
 * desc  : 网络访问管理类，主要初始化OkGo
 */

public class OkGoManager {

    private OkGoManager() {
        //empty
    }

    /**
     * 静态内部类实现单例(实现单例的另外一种单例)
     */
    private static class InstanceHolder{
        private static final OkGoManager instance = new OkGoManager();
    }

    public static OkGoManager getInstance() {
        return InstanceHolder.instance;
    }

    public void initOkGo(Application application) {
        //设置okHttp
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(GlobalConfig.HTTP_CONNECT_TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(GlobalConfig.HTTP_READ_TIME_OUT,TimeUnit.SECONDS);
        builder.writeTimeout(GlobalConfig.HTTP_WRITE_TIME_OUT,TimeUnit.SECONDS);

        //设置log
        if (GlobalConfig.isDebug){
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
            loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
            loggingInterceptor.setColorLevel(Level.INFO);
            builder.addInterceptor(loggingInterceptor);
        }

        //使用sp保持cookie，如果cookie不过期，则一直有效
        //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));
        //使用数据库保持cookie，如果cookie不过期，则一直有效
        builder.cookieJar(new CookieJarImpl(new DBCookieStore(application)));
        //使用内存保持cookie，app退出后，cookie消失
        //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));

        OkGo.getInstance().init(application)
                .setOkHttpClient(builder.build())
                .setCacheMode(CacheMode.NO_CACHE)
                //.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                .setRetryCount(1);
    }
}
